﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Business.Fin;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Sales;
using ESOL.WinUI.Hr;

namespace ESOL.WinUI.Finance
{
    public partial class frmMaintainARRequest : BaseForm.frmBaseDialogyBusinessForm
    {
        #region vars
        public FinReceivedDetailEntity SelectedReceivedDetail { get; set; }
        private List<SalesDeliveryItemEntity> mListDeliveryItem;
        public string SalesProdPlanOrderCode
        {
            get { return txtRelatedOrderId.Text; }
            set { txtRelatedOrderId.Text = value; }
        }
        private string mOrderType;
        public string OrderType
        {
            get { return mOrderType; }
            set { mOrderType = value; }
        }
        private List<SalesDeliveryOrderEntity> salesDeliveryOrderEntities;
        private List<FinReceivedDetailItemEntity> finReceivedDetailItemEntities;
        #endregion

        #region ctors
        public frmMaintainARRequest()
        {
            InitializeComponent();
            if (SelectedReceivedDetail == null)
            {
                SelectedReceivedDetail = new FinReceivedDetailEntity();
                SelectedReceivedDetail.ReceivedDetailId = Guid.NewGuid().ToString();
            }
        }
        public frmMaintainARRequest(List<SalesDeliveryItemEntity> list, MstCustomerEntity customer)
        {
            InitializeComponent();
            if (SelectedReceivedDetail == null)
            {
                SelectedReceivedDetail = new FinReceivedDetailEntity();
                SelectedReceivedDetail.ReceivedDetailId = Guid.NewGuid().ToString();
            }

            mListDeliveryItem = list;
            txtCustomer.Tag = customer;
        }
        #endregion

        #region functions
        private void SetFieldsByCustomer(MstCustomerEntity customer)
        {
            if (customer != null)
            {
                txtCustomer.Tag = customer;
                txtCustomer.Text = customer.CustomerName;
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, customer.CustomerId, false);
                if (cmbCustomerContact.Items.Count > 0)
                {
                    cmbCustomerContact.SelectedIndex = 0;
                    MstCustomerContactEntity entity = (MstCustomerContactEntity)cmbCustomerContact.SelectedItem;
                    if (entity != null)
                    {
                        txtCustomerContactPhone.Text = entity.ContactMobilephone;
                    }
                }
            }
            else
            {
                txtCustomer.Tag = null;
                txtCustomer.Text = "";
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, "", false);
                txtCustomerContactPhone.Text = "";
            }
        }
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItemWithCode(cmbOrderType, "CFT", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbReceivedType, "PAYTYPE", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPayType, "PAT", false);

            DataTable dt = FinReceivedDetailBs.GetBankAccount();
            if (dt != null)
            {
                cmbBankAccount.DataSource = dt;
                cmbBankAccount.DisplayMember = "BANK_ACCOUNT";
                cmbBankAccount.ValueMember = "BANK_ACCOUNT";
            }
        }
        private void SetFields()
        {
            if (ThisActionType == ActionType.New)
            {
                return;
            }
            if (SelectedReceivedDetail == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(SelectedReceivedDetail.CustomerId) == false)
            {
                MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedReceivedDetail.CustomerId);
                SetFieldsByCustomer(customer);
            }
            if (SelectedReceivedDetail.ReceivedDate.ToString("yyyy-MM-dd") == "1900-01-01" ||
                SelectedReceivedDetail.ReceivedDate.ToString("yyyy-MM-dd") == "0001-01-01")
            {
                dtpReceivedDate.EditValue = null;
            }
            else
            {
                dtpReceivedDate.EditValue = SelectedReceivedDetail.ReceivedDate;
            }
            if (ThisActionType == ActionType.New)
            {
                if (CommonParameter.CurrentUser.PersonEntity != null)
                {
                    txtReceivedPerson.Tag = CommonParameter.CurrentUser.PersonEntity;
                    txtReceivedPerson.Text = CommonParameter.CurrentUser.PersonEntity.NameCn + " (" + CommonParameter.CurrentUser.PersonEntity.PersonCode + ")";
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedReceivedDetail.ReceivedPerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedReceivedDetail.ReceivedPerson);
                    if (person != null)
                    {
                        txtReceivedPerson.Tag = person;
                        txtReceivedPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            txtReceivedAmount.Text = SelectedReceivedDetail.ReceivedAmount.ToString("#0.00");
            cmbStatus.SetSelectedValue(SelectedReceivedDetail.Status);
            cmbCurrency.SetSelectedValue(SelectedReceivedDetail.Currency);
            txtInvoiceNo.Text = SelectedReceivedDetail.InvoiceNo;
            txtAccountsCode.Tag = null;
            txtAccountsCode.Text = "";
            if (string.IsNullOrEmpty(SelectedReceivedDetail.AccountsCode) == false)
            {
                FinAccountsEntity account = FinAccountsBs.GetByCode(SelectedReceivedDetail.AccountsCode);
                if (account != null)
                {
                    txtAccountsCode.Tag = account;
                    txtAccountsCode.Text = account.AccountsCode + " " + account.AccountsName;
                }
            }
            cmbOrderType.SetSelectedValue(SelectedReceivedDetail.OrderType);
            cmbReceivedType.SetSelectedValue(SelectedReceivedDetail.ReceivedType);
            cmbPayType.SetSelectedValue(SelectedReceivedDetail.PayType);
            if (string.IsNullOrEmpty(SelectedReceivedDetail.RelatedOrderId) == false)
            {
                SalesProdPlanApplicationEntity salesProdPlanApplication = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(SelectedReceivedDetail.RelatedOrderId);
                if (salesProdPlanApplication != null)
                {
                    txtRelatedOrderId.Text = salesProdPlanApplication.ApplicationCode ;
                    txtRelatedOrderId.Tag = salesProdPlanApplication;
                }
            }            
            cmbBankAccount.Text = SelectedReceivedDetail.BankAccount;
            txtRemark.Text = SelectedReceivedDetail.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedReceivedDetail.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedReceivedDetail.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedReceivedDetail.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedReceivedDetail.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedReceivedDetail.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedReceivedDetail.ApprovedBy);
        }
        private void SetEntity()
        {
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SelectedReceivedDetail.CustomerId = ((MstCustomerEntity)txtCustomer.Tag).CustomerId;
            }
            if (dtpReceivedDate.EditValue!=null)
            {
                SelectedReceivedDetail.ReceivedDate = Convert.ToDateTime(dtpReceivedDate.EditValue.ToString());
            }
            if (txtReceivedPerson.Tag != null && txtReceivedPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedReceivedDetail.ReceivedPerson = ((MstPersonEntity)txtReceivedPerson.Tag).PersonId;
            }
            SelectedReceivedDetail.ReceivedAmount = CommonFunctions.ToDecimal(txtReceivedAmount.Text);
            if (cmbCurrency.SelectedValue != null && cmbCurrency.SelectedValue.ToString().Trim() != "")
            {
                SelectedReceivedDetail.Currency = cmbCurrency.SelectedValue.ToString();
            }
            SelectedReceivedDetail.InvoiceNo = txtInvoiceNo.Text;

            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedReceivedDetail.Status = NormalStatus.STATUS02.ToString();
            }
            if (txtAccountsCode.Tag != null)
            {
                SelectedReceivedDetail.AccountsCode = ((FinAccountsEntity)txtAccountsCode.Tag).AccountsCode;
            }
            if (cmbOrderType.SelectedValue != null && cmbOrderType.SelectedValue.ToString() != "")
            {
                SelectedReceivedDetail.OrderType = cmbOrderType.SelectedValue.ToString();
            }
            if (cmbReceivedType.SelectedValue != null && cmbReceivedType.SelectedValue.ToString() != "")
            {
                SelectedReceivedDetail.ReceivedType = cmbReceivedType.SelectedValue.ToString();
            }
            if (cmbPayType.SelectedValue != null && cmbPayType.SelectedValue.ToString() != "")
            {
                SelectedReceivedDetail.PayType = cmbPayType.SelectedValue.ToString();
            }
            if (txtRelatedOrderId.Tag != null)
            {
                SelectedReceivedDetail.RelatedOrderId = ((SalesProdPlanApplicationEntity)txtRelatedOrderId.Tag).ApplicationId;
            }
            SelectedReceivedDetail.BankAccount = cmbBankAccount.Text;
            SelectedReceivedDetail.Remark = txtRemark.Text;
            if (ThisActionType == ActionType.New)
            {
                SelectedReceivedDetail.CreatedDate = DateTime.Now;
                SelectedReceivedDetail.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedReceivedDetail.LastModifiedDate = DateTime.Now;
                SelectedReceivedDetail.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtReceivedPerson.Text))
            {
                MessageBox.Show("经办人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbCurrency.Text))
            {
                MessageBox.Show("货币种类不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpReceivedDate.EditValue == null)
            {
                MessageBox.Show("收款日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtReceivedAmount.Text))
            {
                MessageBox.Show("收款金额不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbOrderType.Text))
            {
                MessageBox.Show("核算项目不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbReceivedType.Text))
            {
                MessageBox.Show("到账方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    bool isSuccessful = FinReceivedDetailBs.SaveReceivedDetail(true, SelectedReceivedDetail, GetListMap());
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    bool isSuccessful = FinReceivedDetailBs.SaveReceivedDetail(false, SelectedReceivedDetail, GetListMap());
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    SelectedReceivedDetail.ApprovedDate = DateTime.Now;
                    SelectedReceivedDetail.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    GetDeliveryOrdersByGrid();
                    bool isSuccessful = FinReceivedDetailBs.ApproveReceivedDetail(SelectedReceivedDetail, salesDeliveryOrderEntities);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        private void BindDataGrid()
        {
            DataTable dt = FinMapReceivedDeliveryBs.GetDeliveryItemsByDetailId(SelectedReceivedDetail.ReceivedDetailId);
            gvMain.DataSource = dt;

            mListDeliveryItem = new List<SalesDeliveryItemEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                SalesDeliveryItemEntity entity = new SalesDeliveryItemEntity(dr);
                mListDeliveryItem.Add(entity);
            }
        }
        private DataTable GetNewDataTable(DataTable table)
        {
            DataTable dt = FinMapReceivedDeliveryBs.GetDeliveryItemsByDetailId("");
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    DataRow row = dt.NewRow();
                    foreach (DataColumn column in table.Columns)
                    {
                        if (dt.Columns.Contains(column.ColumnName))
                        {
                            row[column.ColumnName] = table.Rows[i][column.ColumnName];
                        }
                    }
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }
        private List<FinMapReceivedDeliveryEntity> GetListMap()
        {
            List<FinMapReceivedDeliveryEntity> list = new List<FinMapReceivedDeliveryEntity>();
            if (gvMain.DataSource == null)
            {
                return list;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (DataRow dr in dt.Rows)
            {
                FinMapReceivedDeliveryEntity entity = new FinMapReceivedDeliveryEntity(dr);
                list.Add(entity);
            }
            return list;
        }
        //获取发货单明细
        private void GetDeliveryOrdersByGrid()
        {
            if (salesDeliveryOrderEntities == null)
            {
                salesDeliveryOrderEntities = new List<SalesDeliveryOrderEntity>();
            }
            DataTable dtDeliveryOrder = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dtDeliveryOrder.Rows)
            {
                SalesDeliveryOrderEntity m = SalesDeliveryOrderBs.GetDeliveryOrderByCode(dr["DELIVERY_ORDER_CODE"].ToString());
                if (m != null)
                {
                    salesDeliveryOrderEntities.Add(m);
                }
            }
        }
        private void ResetAmount()
        {
            decimal itemTotalAmount = 0;
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                itemTotalAmount += CommonFunctions.ToDecimal(dr["ITEM_AMOUNT"]);
            }
            txtReceivedAmount.Text = itemTotalAmount.ToString("#0.00");
        }
        #endregion

        #region events
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SetFieldsByCustomer((MstCustomerEntity)txtCustomer.Tag);
            }
            if (ThisActionType == ActionType.New)
            {
                cmbOrderType.SetSelectedValue(mOrderType);
            }
            BindDataGrid();
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedReceivedDetail = new FinReceivedDetailEntity();
                SelectedReceivedDetail.ReceivedDetailId = Guid.NewGuid().ToString();
                SetFields();
            }
        }
        protected override void Click_Approve()
        {
            if (SelectedReceivedDetail == null)
            {
                return;
            }
            SelectedReceivedDetail.Status = NormalStatus.STATUS03.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (SelectedReceivedDetail == null)
            {
                return;
            }
            SelectedReceivedDetail.Status = NormalStatus.STATUS04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                txtCustomer.Text = frm.SelectedCustomer.CustomerName;
                txtCustomer.Tag = frm.SelectedCustomer;
            }
            else
            {
                txtCustomer.Text = "";
                txtCustomer.Tag = null;
            }
        }

        private void txtReceivedPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtReceivedPerson.Text = frm.SelectedPerson.NameCn+"("+frm.SelectedPerson.PersonCode+")";
                txtReceivedPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtReceivedPerson.Text = "";
                txtReceivedPerson.Tag = null;
            }
        }

        private void txtAccountsCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainFinanceAccountsCode frm = new frmMaintainFinanceAccountsCode();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedAccount != null)
            {
                txtAccountsCode.Text = frm.SelectedAccount.AccountsCode;
                txtAccountsCode.Tag = frm.SelectedAccount;
            }
            else
            {
                txtAccountsCode.Text = "";
                txtAccountsCode.Tag = null;
            }
        }

        private void txtRelatedOrderId_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductPlanApplicationQuery frm = new frmMaintainProductPlanApplicationQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProdPlanApplication != null)
            {
                txtRelatedOrderId.Text = frm.SelectedProdPlanApplication.ApplicationCode;
                txtRelatedOrderId.Tag = frm.SelectedProdPlanApplication;
            }
            else
            {
                txtRelatedOrderId.Text = "";
                txtRelatedOrderId.Tag = null;
            }
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            DataTable dt = gvMain.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (drSelected == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            dt.Rows.Remove(drSelected);
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainDeliveryItemsQuery frm = new frmMaintainDeliveryItemsQuery(true);
            frm.BillingStatus = "未收款";
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedDataTable != null)
            {
                mListDeliveryItem = new List<SalesDeliveryItemEntity>();
                DataTable dt = GetNewDataTable(frm.SelectedDataTable);
                if (dt == null)
                {
                    return;
                }
                gvMain.DataSource = dt;
                foreach (DataRow dr in dt.Rows)
                {
                    SalesDeliveryItemEntity entity = new SalesDeliveryItemEntity(dr);
                    mListDeliveryItem.Add(entity);
                }
                drSelected = ((DataRowView)gridView1.GetFocusedRow()).Row;
            }
            else
            {
                mListDeliveryItem = null;
                gvMain.DataSource = null;
            }
        }

        DataRow drSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridView1.GetFocusedRow() == null)
            {
                return;
            }
            drSelected = ((DataRowView)gridView1.GetFocusedRow()).Row;
        }

        #endregion
    }
}
